dfs and similar dp graphs trees *1700

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;

void findMinReversals(vector<vector<pair<int, int>>> &adjList, vector<bool> &visited, int src, int level, int &rootAns, int &minRes, int oneCount, vector<int> &minNodes){

    visited[src] = true;
    int val = level-2*oneCount;
    if(val < minRes){
        minRes = val;
        minNodes.clear();
        minNodes.push_back(src);
    }
    else if(val == minRes){
        minNodes.push_back(src);
    }

    for(auto p: adjList[src]){
        if(!visited[p.first]){
            rootAns += p.second;
            findMinReversals(adjList, visited, p.first, level+1, rootAns, minRes, oneCount + p.second, minNodes);
        }
    }
}

int main(){


    int n;
    cin >> n;

    vector<vector<pair<int, int>>> adjList(n+1);
    
    for(int i = 1; i <= n-1; i++){
        int u, v;

        cin >> u >> v;

        adjList[u].push_back({v, 0});
        adjList[v].push_back({u, 1});
    }

    vector<bool> visited(n+1, false);
    int minRes = INT_MAX;
    vector<int> minNodes;
    int rootAns = 0;
    findMinReversals(adjList, visited, 1, 0, rootAns, minRes, 0, minNodes);
    sort(minNodes.begin(), minNodes.end());

    cout << rootAns + minRes << endl;

    for(int node: minNodes){
        cout << node << " ";
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

901A - Hashing Trees
1283A - Minutes Before the New Year
1654D - Potion Brewing Class
1107B - Digital root
25A - IQ test
785A - Anton and Polyhedrons
1542B - Plus and Multiply
306A - Candies
1651C - Fault-tolerant Network
870A - Search for Pretty Integers
1174A - Ehab Fails to Be Thanos
1169A - Circle Metro
780C - Andryusha and Colored Balloons
1153A - Serval and Bus
1487C - Minimum Ties
1136A - Nastya Is Reading a Book
1353B - Two Arrays And Swaps
1490E - Accidental Victory
1335A - Candies and Two Sisters
96B - Lucky Numbers (easy)
1151B - Dima and a Bad XOR
1435B - A New Technique
1633A - Div 7
268A - Games
1062B - Math
1294C - Product of Three Numbers
749A - Bachgold Problem
1486B - Eastern Exhibition
1363A - Odd Selection
131B - Opposites Attract